package app.sys.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import app.sys.data.entity.UserInfo;

import java.util.Date;

public class JwtUtils {
    //过期时间
    public static final long EXPIRE_TIME = 60L * 60 * 1000 * 12;

    public static final String SECRET = "SECRET";

    //签发token
    public static String sign(UserInfo user) {
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        return JWT.create()
                .withClaim("userCode", user.getUserCode())
                .withClaim("userName", user.getUserName())
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(SECRET));
    }

    //校验token
    public static boolean verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT decodedJWT = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //获取token内的携带的用户名信息
    public static String getUserNameByToken(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim("userName").asString();
    }

    //获取token内的携带的用户信息
    public static UserInfo getUserByToken(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        UserInfo user = new UserInfo();
        user.setUserCode(decodedJWT.getClaim("userCode").asString());
        user.setUserName(decodedJWT.getClaim("userName").asString());
        return user;
    }
}
